package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    //保存和更新角色操作
    public void saveOrUpdate(Role record) {
        if (record.getId() == null) {
            roleMapper.insert(record);
        } else {
            //先打破关系
            roleMapper.deletePermissionRelation(record.getId());
            roleMapper.deleteMenuRelation(record.getId());
            roleMapper.updateByPrimaryKey(record);
        }
        //循环迭代getPermissions
        for (Permission permission : record.getPermissions()) {
            Long permissionId = permission.getId();
            //插入外键关系
            roleMapper.insertPermissionRelation(record.getId(),permissionId);
        }

        //循环迭代getMenus()
        for (Menu menu : record.getMenus()) {
            Long menuId = menu.getId();
            //插入外键关系
            roleMapper.insertMenuRelation(record.getId(),menuId);
        }

    }

    //查询单个角色操作
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }


    //员工列表操作
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = roleMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Role> data = roleMapper.queryList(qo);
        return new PageResult(count, data);
    }

    /**
     * 根据id删除角色
     * @param id
     */
    public void remove(Long id) {
        //先打破关系
        roleMapper.deletePermissionRelation(id);
        roleMapper.deleteMenuRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 校验
     * @param sn    角色编码
     * @param id    角色ID
     * @return
     */
    public Boolean validateSn(String sn, Long id) {
        //接受传入的部门编号
        Role role = roleMapper.validateSn(sn);
        //如果role找不到 用户名不存在   验证通过 返回true
        //如果前台传过来的id 和数据库查询到id相同 则是相同的用户 在做编辑操作的时候 验证也通过 返回true
        return  role == null || role.getId() == id;
    }

    @Override
    public List<Long> selectByEmployeeId(Long employeeId) {
        return roleMapper.selectByEmployeeId(employeeId);
    }

    /**
     * 根据员工ID查询拥有的角色
     * @param employeeId
     * @return
     */
    public List<String> selectRoleByEmployeeId(Long employeeId) {
        return roleMapper.selectRoleByEmployee(employeeId);
    }
}
